package com.example.module_home.View;

import android.content.ClipboardManager;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.net.Uri;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;

import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;

import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.module_base.Base.BaseActivity;
import com.example.module_home.Adapter.AllOperationAdapter;
import com.example.module_home.DB.DBOperationHelper;
import com.example.module_home.DB.DBOrmLiteHelper;
import com.example.module_home.DB.SeenCodeTable;
import com.example.module_home.Entity.CodeInfo;
import com.example.module_home.Entity.SeenCodeInfo;
import com.example.module_home.Entity.UserOperationInfo;
import com.example.module_home.Module.CodeBank.CodeBankManager;
import com.example.module_home.Public.Constant;
import com.example.module_home.Public.ITHouseTables;
import com.example.module_home.Public.ITHouseTables;
import com.example.module_home.R;
import com.example.module_home.Utils.ClipboardManagerUtil;
import com.example.module_home.Utils.DialogUtil;
import com.example.module_home.databinding.HomeActivityCodeBinding;
import com.example.module_home.databinding.HomeMenuCodeinfoBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.SubscriberMethod;
import org.intellij.lang.annotations.Language;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.List;
import java.util.TreeSet;

import br.tiagohm.markdownview.css.InternalStyleSheet;
import br.tiagohm.markdownview.css.styles.Github;

/**
 * Created by 陈煜 on 2018/4/28.
 */

public class HomeCodeActivity extends BaseActivity<HomeActivityCodeBinding> implements View.OnClickListener{
    private static final String TAG = "HomeCodeActivity";
    private int mCodeId;
    private List<UserOperationInfo> mInfoList;
    private String mPath;
    private PopupWindow mPopupWindow;
    private CodeInfo mCodeInfo;
    private int mSeenNum;
    //    private MyWebViewClient mWebViewClient;

    @Override
    public int setLayout() {
        return R.layout.home_activity_code;
    }

    @Override
    public void init(final HomeActivityCodeBinding bingding) {
        getMainActivityInfo();
        setupToolbar();
        setupWebView();
        setupRightMenu();
        loadWebCode(mCodeId);

    }

    private void loadWebCode(int codeId) {
        CodeBankManager.getInstance(this).getCodeInfo(codeId, DialogUtil.showLoadingDialog(this),new CodeBankManager.CodeBankBack<CodeInfo>() {
            @Override
            public void successful(final CodeInfo info) {
                HomeCodeActivity.this.mCodeInfo = info;
                bingding.setCodeInfo(info);
                SeenCodeTable seenCode = new SeenCodeTable(info.getKindID(),TimeUtils.getNowString(),info.getTitle(),info.getKind(),info.getAuthor());
                try {
                    DBOperationHelper<SeenCodeTable> operationHelper = new DBOperationHelper<>(HomeCodeActivity.this,SeenCodeTable.class);
                    operationHelper.insertData(seenCode);
                    ITHouseTables.seenNum ++;
                    EventBus.getDefault().postSticky(ITHouseTables.seenNum);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
//                if(mWebViewClient ==null){
//                    mWebViewClient = new MyWebViewClient();
//                }
//                mWebViewClient.setCode(info.getCodeData());
//                bingding.webCode.setWebViewClient(mWebViewClient);
//                bingding.webCode.setWebViewClient(new WebViewClient(){
//                    @Override
//                    public void onPageFinished(WebView view, String url) {
//                        super.onPageFinished(view, url);
//                        openEdit(info.getCodeData());
//                    }
//                });
//                openEdit(info.getCodeData());
//                bingding.setCodeInfo(info);
//                InternalStyleSheet style = new Github();
//                bingding.webCode.addStyleSheet(style);
//                bingding.webCode.loadMarkdown(replaceSpace(info.getCode()));
            }

            @Override
            public void failed(int code, String e) {

            }
        });
    }

//    class MyWebViewClient extends WebViewClient{
//        String code;
//
//        public void setCode(String code) {
//            this.code = code;
//        }
//        @Override
//        public void onPageFinished(WebView view, String url) {
//            super.onPageFinished(view, url);
//            openEdit(code);
//        }
//    }


    private void setupWebView() {
        WebSettings settings = bingding.webCode.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setSupportZoom(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        mPath = "file:///android_asset/tinyMce/edit.html";
        bingding.webCode.loadUrl(mPath);
    }

//    @RequiresApi(api= Build.VERSION_CODES.KITKAT)
//    public void openEdit(String code){
//        String content="<p>参考网址：<a href=\"https://www.cnblogs.com/gosky/p/5751815.html\">增删改查</a></p>\n" + "<p>参考网址：</p>\n" + "<hr />\n" + "<div>&nbsp;\n" + "<pre class=\"language-csharp\" contenteditable=\"true\"><span class=\"token comment\" spellcheck=\"true\">//第一步</span>\n" + "<span class=\"token keyword\">using</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">var</span> db <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Entities</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token comment\" spellcheck=\"true\">//Entities为数据库连接类名</span>\n" + "<span class=\"token punctuation\">{</span>\n" + "    <span class=\"token comment\" spellcheck=\"true\">//数据操作</span>\n" + "<span class=\"token punctuation\">}</span>\n" + "</pre>\n" + "</div>";
//        String cc="";
//        try {
//            code= URLEncoder.encode(code,"UTF-8");
//        } catch (UnsupportedEncodingException IE) {
//            IE.printStackTrace();
//        }
//        bingding.webCode.evaluateJavascript("javascript:setHtml('"+code+"')", new ValueCallback<String>() {
//            @Override
//            public void onReceiveValue(String value) {
//                //此处为 js 返回的结果
//            }
//        });
//
//    }

    private void setupRightMenu() {
        CodeBankManager.getInstance(this).getAllOperations(DialogUtil.showLoadingDialog(this), new CodeBankManager.CodeBankBack<List<UserOperationInfo>>() {
            @Override
            public void successful(List<UserOperationInfo> infoList) {
                mInfoList = infoList;
                LinearLayoutManager manager = new LinearLayoutManager(HomeCodeActivity.this);
                manager.setOrientation(LinearLayoutManager.VERTICAL);
                AllOperationAdapter adapter = new AllOperationAdapter(infoList);
                bingding.rightMenu.recyAlloperation.setLayoutManager(manager);
                bingding.rightMenu.recyAlloperation.setAdapter(adapter);
                ViewingCode(adapter);
            }

            @Override
            public void failed(int code, String e) {
                toast(e);
            }
        });
    }

    private void ViewingCode(AllOperationAdapter adapter) {
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Intent intent = new Intent(HomeMainActivity.this, HomeCodeActivity.class);
//                intent.putExtra(Constant.CODE_TITLE,mInfoList.get(position).getTitle());
//                startActivity(intent);
                loadWebCode(mInfoList.get(position).getKindID());
                bingding.drawerLayout.closeDrawer(Gravity.END);

            }
        });
    }


    private String replaceSpace(String str) {
        char[] cs = str.toCharArray();
        int brace = 0;
        boolean quota = false;
        for (int i = 0; i < cs.length; i++) {
            switch (cs[i]) {
                case '>':
                    brace++;
                    break;
                case '<':
                    brace--;
                    break;
                case '"':
                    quota = !quota;
                    break;
                case 32: // ASCII of Space
                    if (!quota && brace==0) cs[i] = '\b';
            }
        }
        return String.valueOf(cs);
    }

    private void getMainActivityInfo() {
        mCodeId = getIntent().getIntExtra(Constant.CODE_ID,-1);
    }


    private void setupToolbar() {
        bingding.lineToolbar.setNavigationIcon(com.example.module_base.R.drawable.ic_arrow_back_black_24dp);
        bingding.lineToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 右上角菜单点击事件
     */
    public void onMenu(View view) {
        // 获取自定义的菜单布局文件
        HomeMenuCodeinfoBinding menuBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.home_menu_codeinfo, null, false);
        // 创建PopupWindow实例,设置菜单宽度和高度为包裹其自身内容
        mPopupWindow = new PopupWindow(menuBinding.getRoot(), ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.WRAP_CONTENT, true);
        //设置菜单显示在按钮的下面
        mPopupWindow.showAsDropDown(findViewById(R.id.more),0,0);
        // 点击其他地方消失
        menuBinding.getRoot().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //如果菜单存在并且为显示状态，就关闭菜单并初始化菜单
                if (mPopupWindow != null && mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                    mPopupWindow = null;
                }
                return false;
            }
        });
        menuBinding.setOnMenuItem(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id==R.id.share_via){
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, mCodeInfo.getCodeData());
            sendIntent.setType("text/plain");
            startActivity(Intent.createChooser(sendIntent, mCodeInfo.getTitle()));
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }else if(id==R.id.copy_link){
            ClipboardManagerUtil.setText(mCodeInfo.getCodeData());
            Snackbar snackbar = Snackbar.make(bingding.webCode, mCodeInfo.getTitle()+"                  已复制到剪贴板",
                    Snackbar.LENGTH_LONG);
            View snackbarView = snackbar.getView();
            snackbarView.setBackgroundColor(ContextCompat.getColor(HomeCodeActivity.this,R.color.lineColor_click));
            snackbar.show();
            mPopupWindow.dismiss();
            mPopupWindow=null;
        }else if(id==R.id.open_with){
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
            startActivity(browserIntent);
            mPopupWindow.dismiss();
            mPopupWindow=null;
        }
    }
}
